<template>
  <div class="loginPage">
    <img src="../assets/LoginImage.png" alt="" class="loginImage"/>
    <div class="loginForm">
      <img src="../assets/logo.png" alt="" />
      <form @submit.prevent>
        <input type="email" placeholder="邮箱" v-model="email" v-if="!isLogin" />
        <input type="text" :placeholder="isLogin ? '用户名或邮箱' : '用户名'" v-model="username" />
        <input type="password" placeholder="密码" v-model="password" />
        <input type="password" placeholder="确认密码" v-model="confirmPw" v-if="!isLogin" />
        <div class="verification" v-if="!isLogin">
          <input type="text" placeholder="邮箱验证码" v-model="verification" />
          <el-button class="getCode" @click="sendCode" :disabled="isDisable">
            {{ isDisable ? `${sec}秒后重新发送` : "获取邮箱验证码" }}
          </el-button>
        </div>
        <button type="submit" class="loginButton" @click="isLogin ? submitLogin() : registerSubmit()">
          {{ isLogin ? "登录" : "注册" }}
        </button>
        <p class="info" @click="isLogin = !isLogin">
          {{ isLogin ? "还没有账号? 点击注册" : "已有账号? 点击登录"}}
        </p>
        <div class="remember" v-if="isLogin">
          <input type="checkbox" v-model="rememberChecked" />自动登录
          <router-link class="link" :to="{ name: 'resetPw' }">忘记密码?</router-link>
        </div>
        <div v-if="!isLogin" class="agreement">
          <input type="checkbox" v-model="agreementChecked"  />勾选表示同意用户使用规范
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { throttle } from "../apis/throttle.js";
import axios from 'axios'
import qs from 'qs'
import { ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { ref, onUpdated, defineProps } from "vue";

const router = useRouter();
const emailReg = /^([A-z0-9]{6,18})(\w|-)+@[A-z0-9]+\.([A-z]{2,3})$/;
let loginStatus = ref(false);
const isLogin = ref(true);
let username = ref("");
let password = ref("");
let confirmPw = ref("");
let verification = ref("");
let agreementChecked = ref(false);
let rememberChecked = ref(false);
let email = ref("");

let isDisable = ref(false);
let buttonCol = ref("#ffa000");
let sec = ref(60);
let data_code = ref("");

onUpdated(() => {
  if (!isLogin.value) {
    document.title = "注册";
  } else {
    document.title = "登录";
  }
})

function getVerificationCode() {
  if (email.value === "") {
    ElMessageBox.alert('请先填写邮箱信息', '警告');
  } else if (emailReg.test(email.value) === false){
    ElMessageBox.alert('邮箱格式错误', '错误');
  } else {
    axios.post("/api/register/sendMail", qs.stringify({
      "email": email.value,
    }))
        .then((response) => {
          let data = response.data;
          if (!data.status) {
            ElMessageBox.alert('未知错误,请联系管理员', '发送失败');
          } else {
            data_code = data.code.toString();
            ElMessageBox.alert('请在3分钟内填写验证码', '发送成功');
            isDisable.value = true;
            buttonCol.value = "#b1d5c8";
            let timer = setInterval(() => {
              sec.value--;
            }, 1000);

            setTimeout(() => {
              clearInterval(timer);
              isDisable.value = false;
              buttonCol.value = "#ffa000";
              sec.value = 60;
            }, 60000);
          }
        })
        .catch((err) => {
          console.log(err);
          ElMessageBox.alert('网络错误，请检查网络连接后重试', '发送失败');
        })
  }
}

let sendCode = throttle(getVerificationCode, 3500);


function login() {
  if (username.value === "") {
    ElMessageBox.alert("请填写您的用户名!", "警告");
  } else if (password.value === "") {
    ElMessageBox.alert("请填写密码!", "警告");
  } else {
    axios.post("/api/login", qs.stringify({
      "username": username.value,
      "password": password.value,
    }))
        .then((response) => {
          console.log(response);
          let data = response.data;
          if (data.status) {
            ElMessageBox.alert(data.msg, "提示");
            router.replace("/");
          } else {
            ElMessageBox.alert(`登录失败: ${data.msg}`, "错误");
          }
        })
        .catch((err) => {
          console.log(err);
          ElMessageBox.alert('网络错误，请检查网络连接后重试', '登录失败');
        })
  }
}
let submitLogin = throttle(login, 2500);

function register() {
  if (!agreementChecked.value) {
    ElMessageBox.alert("请先勾选用户协议", "警告");
  } else if (username.value === "") {
    ElMessageBox.alert("请填写您的用户名!", "警告");
  } else if (password.value === "") {
    ElMessageBox.alert("请填写密码!", "警告");
  } else if (password.value.length < 6 || password.value.length >= 25){
    ElMessageBox.alert("密码长度小于6个字符或大于25个字符!", "警告");
  } else if (password.value !== confirmPw.value) {
    ElMessageBox.alert("密码与确认密码不匹配!", "警告");
  } else if (verification.value === "") {
    ElMessageBox.alert("请填写邮箱验证码!", "警告");
  } else if (verification.value !== data_code) {
    ElMessageBox.alert("验证码错误!", "警告");
  } else if (/^\s+|\s+$/g.test(username.value)) {
    ElMessageBox.alert("用户名不能带空格!", "警告");
  } else {
    axios.post("/api/register", qs.stringify({
      "username": username.value,
      "password": password.value,
      "email": email.value,
    }))
        .then((response) => {
          let data = response.data;
          if (data.status) {
            ElMessageBox.alert(data.msg, "提示");
            isLogin.value = true;
            router.replace("/login");
          } else {
            ElMessageBox.alert(`注册失败: ${data.msg}`, "错误");
          }
        })
        .catch((err) => {
          console.log(err);
          ElMessageBox.alert('网络错误，请检查网络连接后重试', '注册失败');
        })
  }
}
let registerSubmit = throttle(register, 2500);

</script>

<style scoped>
.loginPage {
  display: grid;
  grid-template-columns: 1fr 1fr;
  align-items: center;
  gap: 5vw;
  width: 100vw;
  height: 100vh;
  max-width: 100%;
  background: #f8f9fb;

  padding: 0 10vw;
}

.loginImage {
  border-radius: 15px;
  max-width: 400px;
  position: relative;
  top: -26px;
  left: -30px;
  justify-self: end;
}

.loginForm {
  justify-self: start;
  box-shadow: 0 4px 48px rgba(0, 0, 0, 0.06);
  border-radius: 32px;
  background: white;
  padding: 74px 60px;
  margin-bottom: 32px;

  display: grid;
  place-items: center;
  row-gap: 52px;
  width: 380px;
}

.loginForm > form {
  display: grid;
  row-gap: 24px;
  width: 100%;
  height: 100%;
}

input {
  background: #fafafa;
  border-radius: 8px;
  border: none;
}

input:focus {
  border: 1px #6e9bc5 solid;
  border-radius: 8px;
}

input::placeholder {
  color: #9e9e9e;
}

.loginButton {
  background: linear-gradient(
          89.93deg,
          #00c2ff 0.06%,
          #0047ff 105.68%
  );
  padding: 12px 0;
  color: white;
  border: none;
  border-radius: 40px;
}

.verification {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.verification input {
  width: 55%;
}

.verification .getCode {
  background: v-bind(buttonCol);
  padding: 10px 0;
  width: 40%;
  color: white;
  border: none;
  border-radius: 14px;
}

.info {
  color: #1da0ff;
  text-align: center;
  cursor: pointer;
}

.agreement, .remember {
  color: #a1a1a1;
  display: flex;
  align-items: center;
  gap: 6px;
}

.remember .link {
  cursor: pointer;
  margin-left: 96px;
  color: #1da0ff;
}
</style>